package com.zhi.controller;

import com.zhi.config.Constant;
import com.zhi.entity.Grade;
import com.zhi.entity.Student;
import com.zhi.entity.Teacher;
import com.zhi.entity.User;
import com.zhi.service.*;
import com.zhi.util.MD5Util;
import com.zhi.util.PageUtil;
import com.zhi.util.PubFun;
import com.zhi.util.R;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.List;

@Controller
public class StudentController {

    Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    UserService userService;

    @Autowired
    StudentService studentService;

    @Autowired
    DictionaryService dictionaryService;

    @Autowired
    GradeService gradeService;

    @Autowired
    MaxValueService maxValueService;

    /**
     * 跳转学生列表
     * @param model
     * @param pageUtil
     * @return
     */
//    @RequestMapping("/toHealthRecord")
//    public String toStudent(Model model,PageUtil pageUtil) {
//
//        //1、初始化分页工具
//        pageUtil = PageUtil.init(pageUtil);
//        Pageable pageable = PageRequest.of(pageUtil.getPageIndex()-1, pageUtil.getSize());
//
//        //2、查询分页数据
//        Page<Student> pageList=studentService.getEntityListWithCodeName(pageable);
//        List<Student> students = pageList.getContent();
//
//        //3、设置总页数
//        pageUtil.setTotalPages(pageList.getTotalPages());
//
//        //4、返回前台数据
//        model.addAttribute("pageUtil", pageUtil);
//        model.addAttribute("students", students);
//        return "student/list";
//    }

    /**
     * 跳转增加学生页面
     * @param model
     * @return
     */
    @RequestMapping("/student/toAdd")
    public String toAdd(Model model) {
        //查询所有院系班级
        List<Grade> grades = gradeService.getEntityList();

        model.addAttribute("grades", grades);
        return "student/add";
    }

    /**
     * 增加学生
     * @param student
     * @return
     */
    @RequestMapping("/student/add")
    @ResponseBody
    public R add(Student student) {

        //学生学号：学生标识号+年份+院系班级号后3位+序号，例1001 2016 001 001

        //1获取班级编号后6位,学院3位+班级3位
        String gradeId = student.getGradeId();
        String gradeIdEnd6 = gradeId.substring(gradeId.length()-6);

        //2查询code对应的最大值，若无结果取0并更新1，若有结果取n并更新n+1
        Integer maxvalue = maxValueService.getMax(Constant.ID_BEGIN_STUDENT + gradeIdEnd6);
        if(maxvalue == null){
            maxvalue = 0;
        }
        maxValueService.saveCodeAndValue(Constant.ID_BEGIN_STUDENT+gradeIdEnd6,maxvalue + 1);
        //取得最大值后，补全位数要求
        String studentIdEnd = PubFun.getStandardChar(maxvalue + 1,3);
        //补全编号前缀
        String studentId = Constant.ID_BEGIN_STUDENT + gradeIdEnd6 + studentIdEnd;
        student.setStudentId(studentId);

        //3获得学生证件号，截取后6位作为初始密码
        String idCardNo = student.getIdCardNo();
        String password = idCardNo.substring(idCardNo.length()-6);
        password = MD5Util.md5Encryption(password);//密码MD5加密

        //4存储学信信息表
        studentService.save(student);

        //5新增学生成功后新增对应的user表，为其新增登录用户信息
        //User user = new User(null,studentId,password,Constant.USER_TYPE_STUDENT,Constant.EFFECTIVE_YES);
        //userService.save(user);

        return R.ok();
    }

    /**
     * 跳转编辑学生页面
     * @param model
     * @param id
     * @return
     */
    @RequestMapping("/student/toEdit")
    public String toEdit(Model model,String id) {
        //查询所有院系班级
        List<Grade> grades = gradeService.getEntityList();
        Student student=studentService.getOne(id);

        model.addAttribute("grades", grades);
        model.addAttribute("student", student);

        return "student/edit";
    }

    /**
     * 编辑学生
     * @param student
     * @return
     */
    @RequestMapping("/student/edit")
    public String update(Student student) {
        studentService.edit(student);
        return "redirect:/toStudent";
    }

    /**
     * 删除学生，并删除其对应的登录用户表信息
     * @param id
     * @return
     */
    @RequestMapping("/student/delete")
    public String delete(String id) {

        //1.删除学生表数据
        studentService.delete(id);

        //2.删除学生登录表数据
        userService.deleteByUsernameAndUserType(id,Constant.USER_TYPE_STUDENT);

        return "redirect:/toStudent";
    }

    /**
     * 指导员查看其班级学生
     * @param model
     * @param pageUtil
     * @param httpSession
     * @return
     */
    @RequestMapping("/toStudentForInstructor")
    public String toStudentForInstructor(Model model,PageUtil pageUtil,HttpSession httpSession){

        //获得搜索框输入的条件
        String searchStudentId = pageUtil.getPara01();
        String searchGradeId = pageUtil.getPara02();

        //1、session中获得教师工号teacherId
        Teacher teacher = (Teacher) httpSession.getAttribute("sessionTeacher");
        String teacherId = teacher.getTeacherId();

        //2、查Grade表找该老师作为指导员的班级gradeIds
        Grade grade = new Grade(null,null,null,teacherId,null);
        //2.1查该教师下的所有指导班级，需要这些班级传前台，用于搜索区下拉选
        List<Grade> grades = gradeService.findAll(grade);

        List<Student> students = new ArrayList<>();
        //1、初始化分页工具
        pageUtil = PageUtil.init(pageUtil);
        Pageable pageable = PageRequest.of(pageUtil.getPageIndex()-1, pageUtil.getSize());

        //2.2已查询条件是否输入学号区分
        if(PubFun.isNotNull(searchStudentId)){
            //2.2.1若以学号查询
            //searchGradeId特殊处理下，searchGradeId为null与""，findAll查询有影响，null时不作为参数，""时作为空参数
            //searchGradeId若为""，即代表无班级查询条件，将其置为null
            searchGradeId = searchGradeId==""?null:searchGradeId;
            Student student = new Student();
            student.setStudentId(searchStudentId);
            student.setGradeId(searchGradeId);
            students = studentService.findAll(student);
            //这里先这样写，等把JPA关联表做好了再改
            for(Student s : students){
                s.setGradeId(s.getGrade().getGradeName());
            }
            pageUtil.setTotalPages(1);//有学号做多是1行1页数据
        }else{
            //不以学号查询
            //2.2.1得出班级id再查班级学生
            List<String> gradeIds = new ArrayList<>();
            gradeIds.add("1111");//list增加假数据防止sql in空报错

            //2.2.2若searchGradeId不为空，表示指定查询某班级
            if(PubFun.isNotNull(searchGradeId)){
                gradeIds.add(searchGradeId);
            }else{
                //2.2.3否则查询所有班级
                for(Grade g : grades){
                    gradeIds.add(g.getGradeId());
                }
            }

            //2.2.4、根据班级id查Student,查询分页数据
            Page<Student> pageList=studentService.getEntityListWithCodeName(pageable,gradeIds);
            students = pageList.getContent();

            //2.2.5、设置总页数
            pageUtil.setTotalPages(pageList.getTotalPages());

        }

        //4、返回前台数据
        model.addAttribute("pageUtil", pageUtil);
        model.addAttribute("grades", grades);
        model.addAttribute("students", students);

        return "student/studentForInstructor";
    }


}
